package com.supermap.wzhy.module.mlk.dao;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 名录操作数据类
 * Created by W.Qiong on 16-12-23.
 */
public class MlDao {

    public SessionFactory sessionFactory ;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Map batchSqlExecute(List<String> sqlList, int batchSize) {
        int re = 0;
        Map<String, Object> reMap = new HashMap<>();
        List<Integer> errorList = new ArrayList<>();
        int size = sqlList.size();
        for (int i = 0; i < size; i++) {
            String sql = sqlList.get(i);
            try {
                Query query = sessionFactory.getCurrentSession().createQuery(sql);
                int n = query.executeUpdate();
                re += n > 0 ? n : 0;
                if (i % batchSize == 0) {//批量提交
                    sessionFactory.getCurrentSession().flush();
                    sessionFactory.getCurrentSession().clear();
                }
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                e.printStackTrace(pw);
                pw.flush();
                sw.flush();
                System.out.println(sw.toString());
                errorList.add(i + 1);
                System.out.println("第"+(i + 1)+"异常："+sql);
            }
        }
        if(size==0){
            System.out.println("批量执行SQL空");
        }
        reMap.put("success", re); // 导入成功总数
        reMap.put("error", errorList); // 错误记录
        return reMap;
    }

    public List  query(String sql,Object... args){
        Query query  =  sessionFactory.openSession().createSQLQuery(sql) ;
        for(int i =0 ; i< args.length ;i++){
            query.setParameter(i,args[i]) ;

        }
        try {
            return  query.list() ;
        }   catch (Exception e){
//            System.out.println("错误sql:"+sql);
            e.printStackTrace();
        }
        return  null ;
    }

    public int execute(String sql,Object... args){
        Query query  =  sessionFactory.openSession().createSQLQuery(sql) ;
        for(int i =0 ; i< args.length ;i++){
            query.setParameter(i,args[i]) ;
        }
        try {
            return  query.executeUpdate();
        }   catch (Exception e){
//            System.out.println("错误sql:"+sql);
            e.printStackTrace();
        }
        return 0;
    }
}
